<template>
  <div class="course-detail">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ name: isVideo ? 'VideoList' : 'CourseList' }">
        {{ typeName }}列表
      </el-breadcrumb-item>
      <el-breadcrumb-item>
        {{ editMode ? `编辑${typeName}详情 -- ${title}` : `新增${typeName}详情` }}
      </el-breadcrumb-item>
    </el-breadcrumb>

    <h2>基本信息</h2>
    <el-form
      :model="info"
      :rules="
        info.precised
          ? isVideo
            ? videoWholeRule
            : courseWholeRule
          : isVideo
          ? videoRule
          : courseRule
      "
      label-position="top"
      ref="courseForm"
    >
      <el-form-item prop="title" label="名称">
        <el-input v-model.trim="info.title"></el-input>
      </el-form-item>

      <el-form-item prop="cover" label="封面">
        <div class="cover-box">
          <div class="cover-box-image">
            <img :src="info.cover" />
          </div>
          <upload-resource
            is-public
            @upload="setCoverFile"
            folder="asset"
            :cv-id-path="info.courseId || info.videoId"
          ></upload-resource>

          <div class="cover-box-sys" v-if="coverList">
            系统截图:
            <img
              class="cover-box-item"
              :src="cover"
              v-for="cover in coverList"
              :key="cover"
              :class="{ active: cover === info.cover }"
              @click="setCoverFile({ url: cover })"
            />
          </div>
        </div>
      </el-form-item>

      <el-form-item prop="summary" label="简介">
        <el-input v-model="info.summary"></el-input>
      </el-form-item>

      <el-form-item prop="chapters" label="章节(拖动右边十字排序)" v-if="!isVideo">
        <el-button style="margin-bottom: 10px;" @click="appendChapter" icon="el-icon-plus">
          创建新章节
        </el-button>

        <draggable class="chapters" v-model="info.chapters" handle=".rank-btn">
          <div class="chap" v-for="(chapter, index) in info.chapters" :key="index">
            <span class="chap-order">
              {{ ChapterNumber(index) }}
              <em v-if="!chapter.id">New</em>
            </span>
            <el-input v-model="info.chapters[index].title">
              <el-button
                type="danger"
                slot="append"
                icon="el-icon-delete"
                @click="removeChapter(index)"
              ></el-button>
              <el-button
                type="primary"
                slot="prepend"
                icon="el-icon-rank"
                class="rank-btn"
              ></el-button>
            </el-input>
          </div>
        </draggable>
      </el-form-item>

      <el-form-item prop="intro" label="Web课程介绍">
        <el-row :gutter="10">
          <el-col :span="24">
            <editor
              v-model="info.intro"
              :cv-id-path="info.courseId || info.videoId"
              style="height: 100%"
            ></editor>
          </el-col>
          <!-- <el-col :span="12" class="intro-preview">
            <div v-html="info.intro"></div>
          </el-col> -->
        </el-row>
      </el-form-item>

      <el-form-item prop="guide" label="图文教程" v-if="isVideo">
        <el-row :gutter="10">
          <el-col :span="24">
            <editor
              v-model="info.guide"
              :cv-id-path="info.courseId || info.videoId"
              style="height: 100%"
            ></editor>
          </el-col>
          <!-- <el-col :span="12" class="intro-preview">
            <div v-html="info.guide"></div>
          </el-col> -->
        </el-row>
      </el-form-item>

      <el-form-item prop="authGuide" label=">>>收费<<<图文教程" v-if="isVideo">
        <el-row :gutter="10">
          <el-col :span="24">
            <editor
              v-model="info.authGuide"
              :cv-id-path="info.courseId || info.videoId"
              style="height: 100%"
            ></editor>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item prop="appIntro" label="移动端课程介绍">
        <el-row :gutter="10">
          <el-col :span="24">
            <editor
              v-model="info.appIntro"
              :cv-id-path="info.courseId || info.videoId"
              style="height: 100%"
            ></editor>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item prop="score" label="课程评分">
        <el-input-number
          :controls="false"
          :precision="1"
          :step="0.1"
          v-model="info.score"
        ></el-input-number>
      </el-form-item>

      <el-form-item prop="delicated" label="精品">
        <el-checkbox v-model="info.delicated" :true-label="1" :false-label="0"></el-checkbox>
      </el-form-item>

      <el-form-item prop="preview" label="开启试看" v-if="!isVideo">
        <el-checkbox v-model="info.preview" :true-label="1" :false-label="0"></el-checkbox>
      </el-form-item>

      <el-form-item prop="preview" label="开启片段试看" v-if="isVideo">
        <el-checkbox v-model="info.preview" :true-label="1" :false-label="0"></el-checkbox>
      </el-form-item>

      <el-form-item prop="level" label="课程难度">
        <el-radio-group v-model="info.level">
          <el-radio :label="0">新手入门</el-radio>
          <el-radio :label="1">初级进阶</el-radio>
          <el-radio :label="2">中级拔高</el-radio>
          <el-radio :label="3">高级挑战</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item prop="resources" label="素材" v-if="isVideo">
        <upload-resource is-resource @upload="updateResource"></upload-resource>
        <p style="color: #888;font-size:12px">*多组素材请打为zip压缩包</p>
        <el-tag
          style="margin-right: 5px"
          effect="dark"
          closable
          :type="resource.id ? 'primary' : 'warning'"
          @close="delResource(index)"
          v-for="(resource, index) in info.resources"
          :key="index"
        >
          {{ resource.filename }}
        </el-tag>
      </el-form-item>

      <el-form-item prop="categoryId" label="分类">
        <el-cascader-panel
          v-model="info.categoryId"
          :options="$cateTree"
          :props="{
            value: 'id',
            label: 'title',
            children: 'childs',
            emitPath: false,
          }"
        ></el-cascader-panel>
      </el-form-item>

      <el-form-item prop="tags" :label="`标签(${info.tags.length}/${MAX_TAG_COUNT})`">
        <tag-select v-model="info.tags" :limit="MAX_TAG_COUNT"></tag-select>
      </el-form-item>

      <el-form-item prop="uuids" label="讲师">
        <el-select filterable v-model="info.uuids">
          <el-option
            v-for="(t, index) in $teacherList"
            :key="index"
            :label="t.nickname"
            :value="t.uuid"
          ></el-option>
        </el-select>
      </el-form-item>

      <h2>商品信息</h2>
      <el-form-item prop="payMode" label="付费类型">
        <el-radio-group v-model="info.payMode" @change="payModeChange">
          <el-radio :label="1">VIP免费</el-radio>
          <el-radio :label="2">VIP折扣</el-radio>
          <el-radio :label="3">单点付费</el-radio>
          <el-radio :label="0">免费</el-radio>
          <el-radio :label="4">限时免费</el-radio>
          <el-radio :label="5">限时特价</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="info.payMode !== 0" prop="payPrice" label="价格(元)">
        <!-- <pay-range-sl v-model="info.payPrice" style="width:130px"></pay-range-sl> -->
        <el-input-number
          :controls="false"
          :precision="2"
          :step="0.01"
          v-model.number="info.payPrice"
          placeholder="最多精确到分"
        ></el-input-number>
      </el-form-item>
      <el-form-item prop="showPrice" label="划线价格(元)">
        <el-input-number
          :controls="false"
          :precision="2"
          :step="0.01"
          v-model.number="info.showPrice"
          placeholder="最多精确到分"
        ></el-input-number>
      </el-form-item>

      <h2>上线设置</h2>
      <el-form-item prop="online" label="上线状态">
        <el-radio-group v-model="info.online">
          <el-radio :label="0">待审核</el-radio>
          <el-radio :label="1">上线</el-radio>
          <el-radio :label="2">下线</el-radio>
        </el-radio-group>
      </el-form-item>

      <edit-bar>
        <!-- v-permission="['precised:btn']" -->
        <el-checkbox
          v-model="info.precised"
          :true-label="1"
          :false-label="0"
        >
          设置为已精编
        </el-checkbox>
        <!-- videoID是给视频用的 id是给合集用的 -->
        <el-button type="success" v-if="info.videoId || info.id" @click="save" :loading="saving">
          修改
        </el-button>
        <el-button type="primary" v-else @click="save" :loading="saving">
          新增{{ typeName }}
        </el-button>

        <el-button
          type="primary"
          @click="$tabs.open({ name: 'MediaUpload', params: { id: info.id } })"
          v-if="info.id && !isVideo"
        >
          增加视频
        </el-button>

        <el-button type="danger" @click="$tabs.close()" icon="el-icon-close">
          关闭
        </el-button>
      </edit-bar>
    </el-form>
  </div>
</template>

<script>
  import { cloneDeep } from 'lodash';
  import { FormRuleConf } from '@/config';
  import { ChapterNumber } from 'utils/ChapterNumber';
  import { mapGetters } from 'vuex';
  import EditMixins from 'mixins/Edit';
  import UploadResource from 'comp/UploadResource';
  import TagSelect from 'comp/TagSelect';
  import Editor from 'comp/Editor';
  import EditBar from 'comp/EditBar';

  import CustomSelectData from 'config/CustomSelectData';

  const DATA_TMP = {
    tags: [],
    chapters: [],
    resources: [],
    payMode: 0,
    online: 0,
    delicated: 0,
    preview: 0,
    level: 0,
  };

  const VIDEO_DATA_TMP = {
    tags: [],
    resources: [],
    payMode: 0,
    online: 0,
    delicated: 0,
    preview: 0,
    level: 0,
  };

  export default {
    mixins: [EditMixins],
    data() {
      return {
        info: cloneDeep(this.isVideo ? VIDEO_DATA_TMP : DATA_TMP),
        title: '',
        currentOnlineStatus: 0,
        coverList: [],
        cateList: [],
        chapterList: [],
        teacherList: [],
        MAX_TAG_COUNT: 8,

        ...FormRuleConf.Course,
      };
    },
    computed: {
      isVideo() {
        return this.$route.name === 'VideoDetail';
      },
      typeName() {
        return this.isVideo ? '视频' : '合集';
      },
      editMode() {
        return !!this.info.id || !!this.info.videoId;
      },
      ...mapGetters(['$teacherList', '$cateTree']),
    },
    watch: {
      'info.precised'() {
        this.$refs.courseForm.clearValidate();
      },
    },
    components: {
      UploadResource,
      TagSelect,
      Editor,
      EditBar,
    },
    mounted() {
      // 没有ID就跳走
      if (!this.id) {
        return this.$tabs.close();
      }
    },
    methods: {
      payModeChange(){
        if(this.info.payMode === 0){
          this.info.payPrice = 0
        }
      },
      
      ChapterNumber,

      /**
       * 封面列表
       */
      getCoverList() {
        this.$service
          .AssetVideoSnapshots({
            videoId: this.info.videoId,
          })
          .then((res) => {
            this.coverList = res;
          });
      },
      /**
       * 设置封面
       */
      setCoverFile(data) {
        this.$set(this.info, 'cover', data.url);
      },
      /**
       * 获取合集详情
       */
      getInfo() {
        if (!this.id || this.infoGetting) return;
        // 如果不是这两个页面的话
        if (!['VideoDetail', 'CourseDetail'].includes(this.$route.name)) return;

        const r = this.isVideo ? this.$service.AssetVideoInfo : this.$service.AssetCourseInfo;
        r({ id: this.id })
          .then((res) => {
            this.$set(this, 'info', {
              ...(this.isVideo ? VIDEO_DATA_TMP : DATA_TMP),
              ...res,
            });
            this.currentOnlineStatus = res.online;
            this.title = res.title;

            this.getChapter();

            if (this.isVideo) {
              this.getCoverList();
            }
            // QUAN
            // 处理数据
            // if(this.info.payPrice){
            //   CustomSelectData.payRangeSl.map((item)=>{
            //     if(item.value.indexOf(this.info.payPrice)!==-1){
            //       this.info.payPrice = item.value
            //     }
            //   })
            // }
          })
          .finally(() => [(this.infoGetting = false)]);
      },
      /**
       * 获取章节
       */
      getChapter() {
        if (this.isVideo) return;
        this.$service.AssetChapterList({ courseId: this.id }).then((res) => {
          this.chapterList = [...res];
        });
      },
      appendChapter(data) {
        if (!data.title) {
          this.info.chapters.push({
            title: '',
          });
        }

        this.$set(this.info, 'chapters', this.info.chapters);
      },
      /**
       * 删除章节
       */
      removeChapter(index) {
        // TODO: 删除有问题
        const chapter = this.info.chapters[index];
        if (chapter.id) {
          this.$confirm('确认删除吗?, 删除成功后会清空未保存的章节信息').then(() => {
            this.$service
              .AssetChapterDelete({
                chapterId: this.info.chapters[index].id,
              })
              .then(this.getInfo);
          });
        } else {
          this.info.chapters.splice(index, 1);
          this.$set(this.info, 'chapters', this.info.chapters);
        }
      },
      /**
       * 编辑器更新数据
       */
      catchData(data) {
        this.$set(this.info, 'intro', data);
      },
      /**
       * 保存章节
       */
      saveChapter(chapter) {
        if (!chapter.title) {
          return this.$message.error('填一个章节标题');
        }
        this.$service.AssetChapterSave(chapter, JSON_HEADER).then((res) => {
          this.getChapter();
          this.$message.success('保存成功!');
        });
      },
      /**
       * 删除章节
       */
      delChapter(index) {
        const chapter = this.chapterList[index];
        if (chapter) {
          this.$confirm('确认删除此章节吗?').then(() => {
            if (chapter.id) {
              this.$service.AssetChapterDelete({ chapterId: chapter.id }).then((res) => {
                this.getChapter();
                this.$message.success('删除成功');
              });
            } else {
              this.chapterList.splice(index, 1);
              this.$message.success('删除成功');
            }
          });
        }
      },
      /**
       * 更新素材
       */
      updateResource(data) {
        // this.info.resources.push({
        //   filename: data.name,
        //   url: data.url,
        // });
        // 只允许传1个，多了下载有问题
        this.info.resources = [
          {
            filename: data.name,
            url: data.url,
          },
        ];
      },
      /**
       * 删除素材
       */
      delResource(index) {
        const r = this.info.resources[index];
        if (r) {
          if (r.id) {
            this.$confirm('确认删除这个素材吗?', '提示').then(() => {
              this.$service
                .AssetResourceDelete({
                  resourceId: r.id,
                })
                .then(() => {
                  this.$set(
                    this.info,
                    'resources',
                    this.info.resources.filter((resource) => resource.id !== r.id),
                  );
                });
            });
          } else {
            this.info.resources.splice(index, 1);
            this.$set(this, 'info', this.info);
          }
        }
      },
      /**
       * 保存
       */
      save() {
        if (this.saving) return;

        this.$refs.courseForm.validate((valid) => {
          if (valid) {
            this.saving = true;

            // 处理价格
            // if(this.info.payPrice){
            //   this.info.appleProductId = this.info.payPrice.split(',')[1]
            //   this.info.payPrice = this.info.payPrice.split(',')[0]
            // }else{
            //   this.info.appleProductId = ''
            //   this.info.payPrice = 0
            // }
            const r = this.isVideo
              ? this.$service.AssetVideoSaveall
              : this.$service.AssetCourseSave;

            r(
              {
                ...this.info,
                tagIds: this.info.tags.map((t) => t.id),
              },
              JSON_HEADER,
            )
              .then((res) => {
                this.$message.success('提交成功');
                const id = res || this.info.videoId || this.info.id;

                if (this.isVideo) {
                  this.$tabs.open({ name: 'VideoDetail', params: { id } });
                } else {
                  this.$tabs.open({ name: 'CourseDetail', params: { id } });
                }
              })
              .finally(() => {
                this.saving = false;
              });
          } else {
            this.$message.error('有未填写的内容! 请填写完整');
          }
        });
      },
    },
  };
</script>

<style lang="less" scoped>
  h2 {
    padding-left: 20px;
    border-left: 5px solid #495464;
    line-height: 1;
    margin: 50px 0 10px;
  }

  .intro-preview {
    height: 100%;
    overflow-y: scroll;
    background-color: #eee;
    padding: 5px 10px;
  }

  .chapters {
    width: 500px;
    /deep/ .el-input {
      margin-bottom: 10px;
    }

    .chap {
      display: flex;

      &-order {
        min-width: 110px;
        margin-right: 10px;

        em {
          font-size: 10px;
          color: #ffc600;
        }
      }
    }
  }

  .cover-box {
    display: flex;
    align-items: flex-start;

    &-image {
      width: 200px;
      // height: 150px;
      margin-right: 10px;
      img {
        width: 100%;
        height: 100%;
      }
    }

    &-sys {
      display: flex;
      flex: 1;
      justify-content: flex-start;
      margin-left: 5px;
    }

    &-item {
      width: 200px;
      // height: 100px;
      margin-right: 5px;
      cursor: pointer;
      &.active,
      &:hover {
        border: 2px solid #ffc600;
      }
    }
  }

  .course-detail {
    padding-bottom: 50px;
    .chapter-box {
      margin-top: 50px;
    }

    .chapter {
      padding: 10px;
      border: 2px dashed #ccc;
      margin: 5px 0;
      position: relative;
      min-height: 50px;

      .chapter-body {
        display: flex;
        align-items: center;

        .chapter-title {
          width: 300px;
          margin: 0 10px;
        }
      }
    }
  }

  .editor-bar {
    position: fixed;
    bottom: 0;
    right: 0;
    width: 100%;
    left: 210px;
    background: white;
    padding: 20px;
    border-top: 1px solid #ccc;
    z-index: 11;

    /deep/ .el-button {
      margin-left: 10px;
    }
  }

  /deep/ .el-form-item__label {
    font-size: 16px;
    padding: 10px 5px !important;
    margin-bottom: 10px;
    border-radius: 3px 3px 0 0;
    background: #ced6e2;
    color: #222;
    width: 100%;
    line-height: 24px;
  }
</style>
